import React, { useCallback, useEffect, useRef, useState } from "react";
import api, { types } from '../../api'
import FoodCard from "@/component/FoodCard/FoodCard";
import './modules.scss'

export default function Modules() {
    // 设置 mountedRef 调整set时机
    const mountedRef = useRef<boolean>(true)

    const [modules, setModules] = useState<types.Module[]>([]);

    const execute = useCallback(() => {
        return api.getJSONFile('modules').then(({ data }: { data: types.Module[] }) => {
            if (!mountedRef.current) return null
            setModules(data)
            return data
        });
    }, [])

    useEffect(() => {
        execute()
        return () => {
            mountedRef.current = false
        }
    }, [])

    // 组装模块div
    const getModulesDiv = () => {
        // return modules.map(({ name }) =>
        //     <div key={name}>{name}</div>
        // )

        return modules.map(module => {
            return <FoodCard key={module.name} {...module} />
        })
    }

    return (
        <div className='modules'>
            {getModulesDiv()}
        </div>
    )
}